#define _CRT_SECURE_NO_WARNINGS 1
#include "Heap.h"

void HeapInit(Heap* hp)
{
	assert(hp);
	hp->arr = NULL;
	hp->size = 0;
	hp->capacity = 0;
}

void HeapDestory(Heap* hp)
{
	assert(hp);
	free(hp->arr);
	hp->arr = NULL;
	hp->size = 0;
	hp->capacity = 0;
}

void Swap(HPDataType* a, HPDataType* b)
{
	HPDataType tmp = *a;
	*a = *b;
	*b = tmp;
}

void AdjustUp(HPDataType* arr, int child)
{
	int parents = (child - 1) / 2;
	while (child > 0)
	{
		if (arr[child] < arr[parents])
		{
			Swap(&arr[child], &arr[parents]);
			child = parents;
			parents = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HeapPush(Heap* hp, HPDataType x)
{
	assert(hp);
	//先在数组末尾插入
	if (hp->size == hp->capacity)
	{
		int newcapacity = hp->capacity == 0 ? 4 : 2 * hp->capacity;
		HPDataType* tmp = (HPDataType*)realloc(hp->arr, newcapacity * sizeof(HPDataType));
		if (tmp == NULL)
		{
			perror("realloc fail!\n");
			exit(1);
		}
		hp->arr = tmp;
		hp->capacity = newcapacity;
	}
	hp->arr[hp->size] = x;
	hp->size++;
	//再向上调整建堆
	AdjustUp(hp->arr, hp->size - 1);
}

void AdjustDown(HPDataType* arr, int n, int parents)
{
	//假设法：假设左孩子小
	int child = (parents * 2) + 1;
	//建小堆：谁小谁上去
	while (child < n)	//	child >= n 的时候说明超过了数组长度本身
	{
		if ((child + 1) < n && arr[child + 1] < arr[child])
		{
			child++;
		}
		if (arr[child] < arr[parents])
		{
			Swap(&(arr[child]), &(arr[parents]));
			parents = child;
			child = (parents * 2) + 1;
		}
		else
		{
			break;
		}
	}
}

void HeapPop(Heap* hp)
{
	assert(hp);
	assert(hp->size > 0);
	//堆顶和堆底先交换
	Swap(&(hp->arr[0]), &(hp->arr[hp->size - 1]));
	hp->size--;
	//再向下调整建堆
	AdjustDown(hp->arr, hp->size, 0);
}

HPDataType HeapTop(Heap* hp)
{
	assert(hp);
	assert(hp->size > 0);
	return hp->arr[0];
}

int HeapSize(Heap* hp)
{
	assert(hp);
	return hp->size;
}

bool HeapEmpty(Heap* hp)
{
	assert(hp);
	return hp->size == 0;
}